from helpers import updateInfo
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Main page of website class """

    def get(self):
    
        user=users.get_current_user()
        # Check if user is logged in
        if not user:
            logusername="Anonymous"
            loginurl=users.create_login_url(self.request.uri)
            logintext="Sign In"
        else:
            logusername=user.nickname().capitalize()
            loginurl=users.create_logout_url("/")
            logintext="Sign Out"
        
        q_1 = db.GqlQuery("SELECT * FROM Stocks ORDER BY buydate ASC LIMIT 0,1")
        if q_1.count()==0:
            randtrend="google"
        else:
            if q_1[0].stockref<>None:
                randtrend = q_1[0].stockref.stockname
            else:
                randtrend="google"
        
        q_1 = db.GqlQuery("SELECT *FROM TrendUsers LIMIT 0,10")
        printVal=""
        i=0
        
        for p in q_1:
            # Swtich TDs color
            if i==0:
                classText=" class=\"odd\""
                i=1
            else:
                classText=""
                i=0
            # Update table text with data
            printPercentage, fontColor, changeSign= updateInfo.getPerInfo(p.totalamount/100)
            printVal+="<tr%s><td>%s</td><td><font color=\"%s\">%s%.2f</font></td><td>%.2f</td></tr>" % (classText,p.tuser, fontColor, changeSign, printPercentage, p.totalamount)
    
        # Send data to template
        template_values = {
            'logusername' : logusername,
            'loginurl' : loginurl,
            'logintext' : logintext,
            'printVal' : printVal,
            'randtrend' : randtrend,
            'setHead' : 0,
            'maincontent' : 'mainpage.html'
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
